using System;
using System.Xml;
using DesignByContract;
using Outcoding.GraphGenerator.Entities;
using Outcoding.GraphGenerator.Util.Logging;

namespace Outcoding.GraphGenerator.Composition{
    public class DatatableBuilder : BuilderBase{
        #region Attributes

        private string showKeyAttr = "show-legendkey";
        private string visibleAttr = "visible";

        #endregion

        private readonly string mNodeName = XmlTagNames.datatable.ToString();

        private XmlNode mNode;

        private string mNodePath{
            get { return "./" + mNodeName; }
        }

        public override void SelectNode(XmlDocument document){
            throw new Exception("The method or operation is not implemented.");
        }

        public override void Compose(){
            throw new Exception("The method or operation is not implemented.");
        }

        public override void Compose(XmlNode node){
            mNode = node.SelectSingleNode(mNodePath);
            try{
                BuildObject(mNode);
            }
            catch (PreconditionException preExc){
                LogManager.Instance.LogWarning("Datatable entity could not be created; process aborted.", preExc);
            }
        }

        public override void AppendToParent(object parent){
            Check.Require(parent is Graph, "Parent object not a valid argument");
            ((Graph) parent).TableData = (Datatable) mProduct;
        }

        private void BuildObject(XmlNode datatableXmlNode){
            var datatable = new Datatable();
            try{
                if (datatableXmlNode.Attributes[visibleAttr] != null)
                    datatable.IsVisible = ParseIsVisibleAttribute(datatableXmlNode);
                if (datatableXmlNode.Attributes[showKeyAttr] != null)
                    datatable.IsLegendKeyVisible = ParseLegendKeyttribute(datatableXmlNode);
            }
            catch (PreconditionException preExc){
                //log error
                datatable = null;
                throw;
            }

            mProduct = datatable;
        }

        private bool ParseIsVisibleAttribute(XmlNode datatableXmlNode){
            Check.Require(datatableXmlNode.Attributes[visibleAttr] != null, "visible attribute not present");
            return Boolean.Parse(datatableXmlNode.Attributes[visibleAttr].Value);
        }

        private bool ParseLegendKeyttribute(XmlNode datatableXmlNode){
            Check.Require(datatableXmlNode.Attributes[showKeyAttr] != null, "show-legendkey attribute not present");
            return Boolean.Parse(datatableXmlNode.Attributes[showKeyAttr].Value);
        }
    }
}